package com.core.service.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.core.dao.GenericDao;
import com.core.dao.UserAccountDao;
import com.core.entity.UserAccount;
import com.core.service.UserService;

@Service
public class UserServiceImpl extends GenericServiceImpl<UserAccount, Long>
		implements UserService, Serializable {

	private static final long serialVersionUID = 1133291998507279381L;
	@Autowired
	UserAccountDao userAccountDao;

	@Override
	@Transactional(readOnly=true)
	public UserAccount findByUsername(String username) throws Exception {
		List<UserAccount> result = findAllByProperty("username", username);
		if (result.size() > 0)
			return result.get(0);
		else
			return null;
	}

	@Override
	public GenericDao<UserAccount, Long> getDao() {
		return userAccountDao;
	}

	@Override
	public UserAccount login(String username, String password) throws Exception {
		UserAccount userAccount = findByUsername(username);
		password = new String(DigestUtils.md5DigestAsHex(password.getBytes()));
		if (userAccount != null) {
			System.out.println(password + " | " + userAccount.getPassword());
			if (password.equals(userAccount.getPassword())) {
				return userAccount;
			} else
				throw new Exception("Invalid username or password!");
		} else {
			throw new Exception("Invalid username or password!");
		}
	}
}
